"""
前端日志收集路由
"""
from fastapi import APIRouter, Request
from pydantic import BaseModel
from typing import List, Any, Optional
import json
import os
from datetime import datetime
import logging
from app.schemas.response import ApiResponse

# 设置日志收集器
log_collector_logger = logging.getLogger("frontend_logs")

router = APIRouter()

class LogEntry(BaseModel):
    """日志条目模型"""
    timestamp: str
    level: str
    message: str
    prefix: Optional[str] = None
    params: Optional[Any] = None
    url: Optional[str] = None
    userAgent: Optional[str] = None

class LogRequest(BaseModel):
    """日志请求模型"""
    logs: List[LogEntry]

@router.post("/logs", response_model=ApiResponse)
async def collect_logs(request: Request, log_request: LogRequest):
    """收集前端日志"""
    # 确保日志目录存在
    log_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', 'logs')
    os.makedirs(log_dir, exist_ok=True)
    
    # 日志文件路径
    log_file = os.path.join(log_dir, 'frontend.log')
    
    # 写入日志到文件
    with open(log_file, 'a', encoding='utf-8') as f:
        for log_entry in log_request.logs:
            log_record = {
                'timestamp': log_entry.timestamp,
                'level': log_entry.level,
                'prefix': log_entry.prefix,
                'message': log_entry.message,
                'params': log_entry.params,
                'url': log_entry.url,
                'userAgent': log_entry.userAgent,
                'client_ip': request.client.host
            }
            
            f.write(json.dumps(log_record, ensure_ascii=False) + '\n')
    
    # 同时输出到后端日志系统
    for log_entry in log_request.logs:
        log_message = f"[{log_entry.prefix or 'Frontend'}] {log_entry.level}: {log_entry.message}"
        if log_entry.params:
            log_message += f" Params: {log_entry.params}"
        
        log_collector_logger.info(log_message)
    
    return ApiResponse(
        success=True,
        data={"count": len(log_request.logs)},
        message=f"收集到 {len(log_request.logs)} 条日志"
    )